package models

type BMU struct {
	Model
	StationId   int     `json:"stationId" gorm:"station_id"`
	BSUId       int     `json:"bsuId" gorm:"column:bsu_id;default:null"`
	BCUId       int     `json:"bcuId" gorm:"column:bcu_id;default:null"`
	BatteryNum  int     `json:"batteryNum" gorm:"battery_num"`
	BatteryType int     `json:"batteryType" gorm:"battery_type"`
	Electricity float32 `json:"electricity"`
	Status      int     `json:"status"`
}

func GetBMUById(id int) BMU {
	var bmu BMU
	db.Where("id = ?", id).First(&bmu)
	return bmu
}

func GetBMUsForUser(userId int) (bmus []BMU){
	var employments []Employment
	db.Table("bms_employment").Where("employer_id = ? or employee_id =?", userId, userId).Scan(&employments)
	for _, e := range employments {
		var tmp []BMU
		db.Where("station_id = ?", e.StationId).Find(&tmp)
		for _, t := range tmp {
			bmus = append(bmus, t)
		}
	}
	return
}

func GetBMUsByStationId(stationId int) (bmus []BMU) {
	db.Table("bms_bmu").Where("station_id = ?", stationId).Scan(&bmus)
	return
}

func GetBMUsByBSUId(bsuId int) (bmus []BMU) {
	db.Table("bms_bmu").Where("bsu_id = ?", bsuId).Scan(&bmus)
	return
}

func GetBMUsByBCUId(bcuId int) (bmus []BMU) {
	db.Table("bms_bmu").Where("bcu_id = ?", bcuId).Scan(&bmus)
	return
}

func ExistBMUById(id int) bool {
	var bmu BMU
	db.Select("id").Where("id = ?", id).First(&bmu)
	return bmu.ID > 0
}

func AddBMU(id, stationId, batteryNum, batteryType int) bool {
	db.Create(&BMU{
		Model: Model{ID: id},
		StationId: stationId,
		BatteryNum: batteryNum,
		BatteryType: batteryType,
	})
	return true
}

func AddBMUWithBSU(id, stationId, bsuId, batteryNum, batteryType int) bool {
	db.Create(&BMU{
		Model: Model{ID: id},
		StationId: stationId,
		BSUId: bsuId,
		BatteryNum: batteryNum,
		BatteryType: batteryType,
	})
	return true
}

func AddBMUWithBCU(id, stationId, bcuId, batteryNum, batteryType int) bool {
	db.Create(&BMU{
		Model: Model{ID: id},
		StationId: stationId,
		BCUId: bcuId,
		BatteryNum: batteryNum,
		BatteryType: batteryType,
	})
	return true
}

func AddBMUComplete(id, stationId, bsuId, bcuId, batteryNum, batteryType int) bool {
	db.Create(&BMU{
		Model: Model{ID: id},
		StationId: stationId,
		BSUId: bsuId,
		BCUId: bcuId,
		BatteryNum: batteryNum,
		BatteryType: batteryType,
	})
	return true
}

func DeleteBMU(id int) bool {
	db.Where("id = ?", id).Delete(&BMU{})
	return true
}

func UpdateBMU(id int, data interface{}) bool {
	db.Model(&BMU{}).Where("id = ?", id).Updates(data)
	return true
}